//
//  DJAppRestorAlterView.m
//  Huaya
//
//  Created by huaya on 2025/3/28.
//  Copyright © 2025 HY. All rights reserved.
//

#import "DJAppRestorAlterView.h"

#import "AppDelegate.h"

@interface DJAppRestorAlterView ()
@property (weak, nonatomic) IBOutlet UIView *bgView;
@property (weak, nonatomic) IBOutlet UIView *centerView;
@property (weak, nonatomic) IBOutlet UILabel *titleLab;
@property (weak, nonatomic) IBOutlet UILabel *contentLab;
@property (weak, nonatomic) IBOutlet UIView *btnView;
@property (weak, nonatomic) IBOutlet UILabel *btnLab;
@property (weak, nonatomic) IBOutlet UIButton *ykBtn;
@property (weak, nonatomic) IBOutlet UIView *lottieLoadView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *centerViewConst;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *btnConst;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *centerViewHeightConst;
@property (nonatomic, strong) NSString *innerType;
@property (nonatomic, strong) NSTimer *countdownTimer;
@property (nonatomic, assign) NSInteger secondsLeft;    // 剩余秒数
@end

@implementation DJAppRestorAlterView
// 启动倒计时
- (void)startCountdown {
    self.secondsLeft = 10; // 初始化剩余时间
    // 创建计时器（每秒触发一次）
    self.countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                           target:self
                                                         selector:@selector(updateCountdown)
                                                         userInfo:nil
                                                          repeats:YES];
}
// 计时器回调方法（每秒执行）
- (void)updateCountdown {
    self.secondsLeft--; // 剩余秒数减1
    
    // 更新 UI（例如显示剩余时间）
    NSLog(@"剩余时间：%ld 秒", (long)self.secondsLeft);
    
    // 倒计时结束
    if (self.secondsLeft <= 0) {
        [self.countdownTimer invalidate]; // 销毁计时器
        self.countdownTimer = nil;
        
        [self action]; // 执行目标方法
    }
}

// 倒计时结束后执行的方法
- (void)action {
    NSLog(@"倒计时结束，执行操作！");
    
//    [MKUtils showToast:@"同步失败，请确认后重试"];
    
    [self hidAction];
}

- (IBAction)closeAction:(id)sender {
    
    [self hidAction];
}
+ (instancetype)createViewWithType:(NSString *)innerType{
    DJAppRestorAlterView *view = [[[NSBundle mainBundle] loadNibNamed:@"DJAppRestorAlterView" owner:nil options:nil] lastObject];
    view.innerType = innerType;
    return view;
}
- (void)awakeFromNib{
    [super awakeFromNib];
    self.lottieLoadView.hidden = YES;
    [self.bgView setBackgroundColor:[UIColor colorWithWhite:0 alpha:0]];
    self.centerViewConst.constant = kScreenHeight/2+234;
    self.btnView.layer.cornerRadius = self.btnView.frame.size.height/2;
    self.centerView.layer.cornerRadius = 8;
    self.ykBtn.layer.masksToBounds = YES;
    self.ykBtn.layer.cornerRadius = self.ykBtn.frame.size.height/2;;
    
    UITapGestureRecognizer *tapGest = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestAction)];
    
    [self.btnView addGestureRecognizer:tapGest];
    
    [MKApplePayUtils sharedInstance].restoreCancelBlock = ^{
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.lottieLoadView.hidden = YES;
            [self.lottieLoadView removeAllSubviews];
            self.btnLab.text = @"Sync Now";
            self.btnConst.constant = 0;
            if (self.countdownTimer) {
                [self.countdownTimer invalidate];
                self.countdownTimer = nil;
            }
            [self layoutIfNeeded];
        });
        
    };
    
    [MKApplePayUtils sharedInstance].completeTransactionBlock = ^{
        
        [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeSuccess alertTitle:@"Success"];
        
        [self hidAction];
        
        MK_BLOCK_EXEC(self.reloadDataBlock);
        
    };
    
}
- (IBAction)ykAction:(id)sender {
    
    if (self.ykBlock) {
        self.ykBlock();
    }
    [self closeAction:nil];
    
}
- (void)tapGestAction{
    
    if ([self.innerType isEqualToString:@"0"]) {
        if (self.loginBlock) {
            self.loginBlock();
        }
        [self closeAction:nil];
    }else{
        
        [[MKApplePayUtils sharedInstance] restorePurchases];
        
        TLLottieView *aniView = [[TLLottieView alloc] initWithName:@"lottie_loading_Restor"];
        aniView.frame = self.lottieLoadView.bounds;
        aniView.loopAnimationCount = -1;
        [self.lottieLoadView addSubview:aniView];
        [aniView play];
        
        self.btnLab.text = @"Syncing";
        self.btnConst.constant = 10;
        self.lottieLoadView.hidden = NO;
        [self layoutIfNeeded];
        [self startCountdown];
    }
    
}
- (void)setInnerType:(NSString *)innerType{
    if (innerType) {
        _innerType = innerType;
        if ([innerType isEqualToString:@"0"]) {
            self.ykBtn.hidden = NO;
            self.titleLab.text = @"Guest Purchase Notice";
            self.contentLab.text = @"Purchase without registration. After signing up, you can access your purchased content on all devices.";
            self.btnLab.text = @"Sign In to Buy";
            self.centerViewHeightConst.constant = 274;
        }else{
            self.ykBtn.hidden = YES;
            self.titleLab.text = @"Restore Purchases";
            self.contentLab.text = @"If you have paid and received Apple's receipt order. However, if the goods have not arrived, you can click the sync button to synchronize the purchase status.";
            self.centerViewHeightConst.constant = 244;
        }
        [self layoutIfNeeded];
    }
}
- (void)showAction{
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [delegate.window addSubview:self];
    [self mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(delegate.window);
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:0.5 animations:^{
            [self.bgView setBackgroundColor:[UIColor colorWithWhite:0 alpha:0.6]];
            self.centerViewConst.constant = 0;
            [self layoutIfNeeded];
        }];
    });
}

- (void)hidAction{
    [UIView animateWithDuration:0.5 animations:^{
        [self.bgView setBackgroundColor:[UIColor colorWithWhite:0 alpha:0.6]];
        self.centerViewConst.constant = 0;
        [self layoutIfNeeded];
    }completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

@end
